# -*- coding: utf-8 *-*

#   This file is part of Sql-Rice.
#
#    Sql-Rice is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    Sql-Rice is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Sql-Rice; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
import collections


FieldName = collections.namedtuple('FieldName', 'index name')


class DBSET(object):

    def __init__(self, statements, connection, dbapi):
        self.statement = statements
        self.connection_data = connection
        self.dbapi = __import__(dbapi, globals())

    def execute(self, sql, params, auto_commit=False):
        conn = self.dbapi.connect(**self.connection_data)
        cursor = conn.cursor()
        ret = cursor.execute(sql, params)
        if auto_commit:
            conn.commit()
        return ret

    def search(self, params):
        sql = self.statement['select']
        cursor = self.execute(sql, params)
        ret = []
        field = [FieldName(index, name[0]) for index, name
                    in enumerate(cursor.description)]
        for row in cursor:
            ret.append(dict((f.name, row[f.index]) for f in field))
        return tuple(ret)

    def update(self, params):
        sql = self.statement['update']
        self.execute(sql, params, True)

    def new(self, params):
        sql = self.statement['insert']
        self.execute(sql, params, True)

    def delete(self, params):
        sql = self.statement['delete']
        self.execute(sql, params, True)
